from typing import List


class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        cnt=0  # 统计出现的次数
        n=len(nums)
        if n<=2:
            return n
        i=1
        while i<n:
            if nums[i]==nums[i-1]:
                cnt+=1
            else:
                cnt=0
            if cnt>=2:
                nums.pop(i)  # 删除当前下标
                n-=1  # 个数-1
                continue
            i+=1  # 遍历下一个
        return n

# 方法二：原地栈
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        # 原地栈

        stack_size = 2  # 栈的大小，前两个元素默认保留
        for i in range(2, len(nums)):
            if nums[i] != nums[stack_size - 2]:  # 和栈顶下方的元素比较
                nums[stack_size] = nums[i]  # 入栈
                stack_size += 1
        return min(stack_size, len(nums))

